[中文]
https://blog.csdn.net/hsk256/article/details/49104955
https://dongchuan.gitbooks.io/java-interview-question/
[英文]
https://www.edureka.co/blog/interview-questions/java-interview-questions/#basic
https://www.javatpoint.com/corejava-interview-questions
[Coding Interview]
http://javarevisited.blogspot.sg/2017/07/top-50-java-programs-from-coding-Interviews.html
Polymorphism [pao ni mo fei zen]
enumerate[en nu me rui te]
#Java总结
###1.What is the JVM? What is “write once, run anywhere”? Are there negatives?
JVM stands for Java Virtual Machine,
【Its a container to run Java byte code, also a process】
Java code —compiled—> byte code,
JVM is then responsible for executing this byte code.
No need to compile and test the application separately on every platform.
This is at the cost of speed. The extra layer of the JVM means it is slower than direct-to-tin languages like C
###2.What is JIT
JIT stands for “Just in Time”.
As discussed, the JVM executes bytecode.
However, if it determines a section of code is being run frequently it can optionally compile a section down to native code to increase the speed of execution.
The smallest block that can be JIT compiled is a method.
####3. JRE and JDK?
JDK > JRE > JVM
JRE (Java Runtime Environment) :
JRE is a software package that contains what is required to run a Java program. It’s an implementation of the JVMJDK(Java Development Kit) :
It is the tool necessary to compile, document and package Java programs.
Along with JRE, it includes an interpreter/loader, a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.It contains JRE + development tools.
###4. Explain: public static void main(String args[]).
public : Public is an access modifier(访问修饰符),Public means that this Method will be accessible by any Class.
static : (Non-access modifiers)it can be accessed without creating the instance of a Class.
void : It is the return type of the method.
main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only.
It is the method where the main execution occurs.String args[] : It is the parameter passed to the main method.
Non-access modifiers:
Static:
变量:
used to refer property of all objects
The static variable gets memory only once in class area at the time of class loading.【Why main method is static 】because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
static block:
Is used to initialize the static data member.
It is executed before main method at the time of classloading.final:
变量:不能再被重新赋值
方法可以继承,但不可以修改
类不能被继承
Final is used to apply restrictions on class, method and variable.
Final class can’t be inherited,
final method can’t be overridden and
final variable value can’t be changed.abstract
抽象类:不能用来实例化对象
抽象方法:没有任何实现的方法,该方法的的具体实现由子类提供
###5. Override & Overload
static(静态绑定) 和 private 不能被Override(动态绑定)
Overload:
only happens between sub class and parent class
In Method Overriding, sub class have the same method with same name, same type of parameters and same return type as a super class.
子类调用父类:Super
子类访问自己:thisOverloading :
In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.
###6. Inherent
- extends
Implement
public interface A {public void eat();} public interface B {public void show();} public class C implements A,B {}
###7. Primitive data types & 什么是自动拆装箱(wrapper classes)
byte,shot,int,long,float,double,char,boolean,void
converts the java primitives into the reference types(Object)
因为集合(Collection)只接收对象,java1.5之前需要手动转换。
【Java是值传递】
为什么引用类型 可以被改变?因为我们传的这个值是地址
对于引用类型 str,赋值运算符会改变引用中所保存的地址,原来的地址被覆盖掉。但是原来的对象不会被改变(重要)
###8. object & class & constructors
A class is an template/blueprint that determines how an object will behave and what the object will contain
An object is the entity when the code are running, it has specify states and behaviors.
constructor refers to a block of code which is used to initialize an object (can not be final)
###9. 接口和抽象类的区别是什么?Interface & Abstract class
不同点在于:
抽象类中的方法可以有方法体,就是能实现方法的具体功能,但是接口中的方法不行。
An abstract class can have non-abstract methods.
An Interface cannot contain constructors抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是 public static final 类型的
An Interface cannot have instance variables接口中不能含有静态代码块以及静态方法(用 static 修饰的方法),而抽象类是可以有静态代码块和静态方法。
- 一个类只能继承一个抽象类,而一个类却可以实现多个接口。
A Class may implement several interfaces.
###10 Sort
Quick sort for primitive type
Merger sort for object
Average : both nlog(n)
worst: quicksort : n^2
Mergersort : nlog(n)
###11 JVM Component
- Method Area
存储已被虚拟机加载的类的信息、常量、静态变量和即时编译器编译后的代码等数据
Stores information about classes that have been loaded by the virtual machine, constants, static variables, and code compiled by the just-in-time compiler
- Heap (Allocate storage space for instances happens here)
JVM language Stacks
用于存储局部变量表、操作数栈、动态链接和方法出口等信息。 Used to store information such as local variable tables, operand stacks, dynamic links, and method exits.
Native Method Stacks
- PC registers
###12 如何判断一个对象是否存活(GC对象的判定)
Marking Reachable Objects
- GC defines some specific objects as Garbage Collection Roots
- Local variable and input parameters of the currently executing methods
- Active threads
- Static field of the loaded classes
- JNI references
- GC traverses the whole object graph in your memory, starting from those Garbage Collection Roots and following references from the roots to other objects
可达性算法(引用链法)
该算法的思想是:从一个被称为GC Roots的对象开始向下搜索,如果一个对象到GC Roots没有任何引用链相连时,则说明此对象不可用。
虚拟机栈中引用的对象
方法区类静态属性引用的对象
方法区常量池引用的对象
本地方法栈JNI引用的对象
###13. 简述java垃圾回收机制?
在JVM中,有一个垃圾回收线程
在虚拟机空闲或者当前堆内存不足时,才会触发执行
扫面那些没有被任何引用的对象,并将它们添加到要回收的集合中,进行回收。
###14. java中垃圾收集的方法有哪些?
Mark and Sweep 标记-清除:
它的思想就是标记哪些要被回收的对象,然后统一回收
Mark and Sweep and Compact 标记-整理
该算法主要是为了解决标记-清除,产生大量内存碎片的问题;当对象存活率较高时,也解决了复制算法的效率问题。它的不同之处就是在清除对象的时候现将可回收对象移动到一端,然后清除掉端边界以外的对象,这样就不会产生内存碎片了
Mark and Copy 复制算法
复制算法将可用内存按容量划分为相等的两部分,然后每次只使用其中的一块,当一块内存用完时,就将还存活的对象复制到第二块内存上,然后一次性清楚完第一块内存,再将第二块上的对象复制到第一块。但是这种方式,内存的代价太高,每次基本上都要浪费一般的内存。
【于是将该算法进行了改进】内存区域不再是按照1:1去划分,而是将内存划分为8:1:1三部分,较大那份内存交Eden区,其余是两块较小的内存区叫Survior区。每次都会优先使用Eden区,若Eden区满,就将对象复制到第二块内存区上,然后清除Eden区,如果此时存活的对象太多,以至于Survivor不够时,会将这些对象通过分配担保机制复制到老年代中
- 分代收集 Generational collection?
现在的虚拟机垃圾收集大多采用这种方式,它根据对象的生存周期,将堆分为新生代和老年代。在新生代中,由于对象生存期短,每次回收都会有大量对象死去,那么这时就采用复制算法。老年代里的对象存活率较高,没有额外的空间进行分配担保,所以可以使用标记-整理 或者 标记-清除。
###15. What is the difference between equals() and == ?
Equals() method is defined in Object class in Java and used for checking equality of two objects
“==” used to compare primitives and objects.
###16. (堆内存 & 栈内存) Heap & Stack Memory?
- Memory : Stack memory is used only by one thread of execution.
- Access : Stack memory can’t be accessed by other threads.
Memory Management :
Stack Follows LIFO manner to free memory. Heap :Memory management is based on generation associated to each object.
Lifetime
Stack :Exists until the end of execution of the thread. Heap memory lives from the start till the end of application execution.
Usage
Stack memory only contains local primitive and reference variables to objects in heap space. Heap: Whenever an object is created, it’s always stored in the Heap space.
###17. HashMap的工作原理是什么?
【Which data structure is used to implement HashMap in Java? 】
It is internally implemented by using an array and linked list data structure in JDK.
The array is used as bucket while a linked list is used to store all mappings which land in the same bucket.
【How does put() method of HashMap works in Java? 】
It is responsible for storing an object into backend array. The hashcode() method is used in conjunction with a hash function to find the correct location for the object into the bucket. If a collision occurs then the entry object which contains both key and value is added to a linked list and that linked list is stored into the bucket location.
【】
You can store NULL value
HashMap is not thread-safe
【Hashmap & Hashtable】
- HashTable基于Dictionary类 ,而HashMap是基于AbstractMap
- HashMap的key和value都允许为null,而Hashtable的key和value都不允许为null。
- Hashtable是同步的,而HashMap是非同步的,但是我们也可以通过Collections.synchronizedMap(hashMap),使其实现同步。
###18. 同步和异步的区别
同步:发送一个请求,等待返回,然后再发送下一个请求
异步:发送一个请求,不等待返回,随时可以再发送下一个请求
同步可以避免出现死锁,读脏数据的发生,一个需要等待,一个不需要等待。
###19 遍历一个List
List<String> strList = new ArrayList<>();
//for-each
for(String str:strList) {
System.out.print(str);
}
//use iterator 尽量使用这种 更安全(fail-fast)
Iterator<String> it = strList.iterator();
while(it.hasNext) {
System.out.printf(it.next());
}
###20 遍历一个Hashmap
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
###22 哪些集合类提供对元素的随机访问?
ArrayList、HashMap、TreeMap和HashTable类
###23 LinkedList和ArrayList的区别是什么?
- 对于需要快速插入、删除元素,则需使用 LinkedList。
- 对于需要快速访问元素,则需使用 ArrayList
###24 What is the difference between Array list and vector?
- Array List is not synchronized, so is faster
- Array List can only use Iterator for traversing an Array List.
- Vector can uses both Enumeration and Iterator.
###25. What is Object Oriented Programming?
Object Oriented Programming (OOP) is a programming paradigm where the complete software operates as a bunch of objects talking to each other. An object is a collection of data and methods that operate on its data.
###26. What are main features of OOP?
Encapsulation
1) Data hiding: A language feature to restrict access to members of an object. For example, private and protected members in JAVA.
2) Bundling of data and methods together: Data and methods that operate on that data are bundled together.
Polymorphism
some code or operations or objects behave differently in different contexts.Inheritance
a class is based on another class and uses data and implementation of the other class
###27 Exception
Q7. How to create a custom Exception?
To create you own exception extend the Exception class or any of its subclasses.
class New1Exception extends Exception { }
// this will create Checked Exception
class NewException extends IOExcpetion { }
// this will create Checked exception
class NewException extends NullPonterExcpetion { }
// this will create UnChecked exception
###28 Error and Exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.
###29. How can you handle Java exceptions?
There are five keywords used to handle exceptions in java:
try
catch
finally
throw
throws
###30. What are the differences between Checked Exception and Unchecked Exception?
Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
Checked exceptions are checked at compile-time.
Example: IOException, SQLException etc.Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions.
Unchecked exceptions are not checked at compile-time.
Example: ArithmeticException, NullPointerException etc.
-
1.为什么要接口,为什么要抽象类,接口和抽象类有什么区别
https://www.zhihu.com/question/20111251
https://www.javatpoint.com/collections-in-java
-
在Linux上,对于多进程,子进程继承了父进程的下列哪些:
共享内存 信号掩码 已打开的文件描述符磁盘 平均寻道长度
https://www.nowcoder.com/test/question/done?tid=14763886&qid=51665#summary
iP地址为140.123.0.0的地址是B类地址,若要切割为10个子网,而且都要连接上Internet,请问子网掩码应设为()
https://www.nowcoder.com/test/question/done?tid=14763886&qid=51667#summary
默认B类地址的子网掩码是/16,也就是255.255.0.0
切割成10个子网的话,就得向主机位借2的四次方=16>10,即向主机位借4位。
所以子网掩码要设置成/20,也就是255.255.240.0路由汇聚
https://www.nowcoder.com/test/question/done?tid=14763886&qid=51672#summary系统开销所占比
https://www.nowcoder.com/test/question/done?tid=14763886&qid=51675#summary
值类型和引用类型的区别
https://www.nowcoder.com/test/question/done?tid=14763886&qid=51679#summaryisPrime
static boolean IsPrime(int num) { boolean ret = true; int ubound =(int) (Math.sqrt(num)+1); for (int i = 2; i < ubound; i++) { if (num % i == 0) { ret = false; break; } } return ret; }
- 当try区段不论程序是否发生错误及捕捉到异常情况,都会执行finally部分
- Statement执行扫描的结果集比PreparedStatement大